package com.kh.pajx.sop.view.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.kh.pajx.sop.base.DatabaseContextHolder;
import com.kh.pajx.sop.domain.SOPCurrentUser;
import com.kh.pajx.sop.util.web.CSRFTokenManager;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 权限验证拦截器
 * @author:	azzcsimp
 * @Createdate:	2014年6月26日 下午2:07:15
 */
public class CheckPrivilegeInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 3731745165953737050L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_HOMESCHOOL);
		// 获取当前登录用户
		SOPCurrentUser currentUser = (SOPCurrentUser) ActionContext.getContext().getSession()
				.get("currentUser");

		// 获取当前访问的URL，并去掉当前应用程序的前缀 namespaceName +actionName
		String namespace = invocation.getProxy().getNamespace();
		String actionName = invocation.getProxy().getActionName();
		String privilegeUrl = null;
		if (namespace.endsWith("/")) {
			privilegeUrl = namespace + actionName;
		} else {
			privilegeUrl = namespace + "/" + actionName;
		}

		// 要去掉开头的'/'
		if (privilegeUrl.startsWith("/")) {
			privilegeUrl = privilegeUrl.substring(1);
		}
		
		// 如果未登录用户
		if(currentUser == null){
			if(privilegeUrl.startsWith("login_login")){
				// 如果正在使用登录功能，放行
				return invocation.invoke();
			} else {
				HttpServletRequest request = ServletActionContext.getRequest();
				// 如果不是去登录，就转到登录页面
				if ("XMLHttpRequest".equalsIgnoreCase(request
						.getHeader("X-Requested-With"))
						|| request.getParameter("ajax") != null) {
					//PrintWriter out = response.getWriter();
					//out.println({"statusCode":"301", "message":"Session Timeout! Please re-sign in!"});
					HttpServletResponse response = ServletActionContext.getResponse();
					response.setHeader("Pragma", "No-Cache");
					response.setHeader("Cache-Control", "No-Cache");
					response.setDateHeader("Expires", 0);
					response.setCharacterEncoding("utf-8");
					String timeOutStr = "{\"statusCode\":\"301\", \"message\":\"session超时，请重新登录!\"}";
					response.getWriter().write(timeOutStr);
					return null;
				} else {
					//response.sendRedirect(response.encodeRedirectURL(this.loginUrl + java.net.URLEncoder.encode(backToUrl, "UTF-8")));
					ActionContext.getContext().put("csrfToken", CSRFTokenManager.getTokenForSession(ServletActionContext.getRequest().getSession()));
					return "login";
				}
			}
		// 如果已登录用户判断权限
		} else { 
			if(currentUser.getInsideUser().isAdmin()){
				return invocation.invoke();
			}
			if(currentUser.getUserRole().hasPrivilegeByUrl(privilegeUrl + ".action")){
				return invocation.invoke();
			}else{
				return "noPrivilegeError";
			}
		}
	}
}
